package com.itheima;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtText {
    /**
     * 生成JWT令牌
     */
    @Test
    public void testGenJwt() {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", 1);
        claims.put("name", "zhangsan");
        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, "aXRjYXN0")
                .addClaims(claims) // 指定自定义的负载信息
                .setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000)) // 指定令牌的过期时间
                .compact();
        System.out.println(jwt);
    }

    /**
     * 解析JWT令牌
     */
    @Test
    public void textParseJWT(){
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJpZCI6MSwiZXhwIjoxNzQ0NDQ2OTg1fQ.p_Sye5yGip198cbuASDmE2eEPRswPC3MTvatU7IBhTY";
        Claims claims = Jwts.parser().setSigningKey("aXRjYXN0")
                .parseClaimsJws(token)
                .getBody();
        System.out.println(claims);
    }
}
